package com.xyzwps.mvckotlin.handler

import com.xyzwps.mvckotlin.exception.unhandled
import com.xyzwps.mvckotlin.handler.helper.body
import com.xyzwps.mvckotlin.handler.helper.json
import com.xyzwps.mvckotlin.handler.helper.render
import kotlinx.coroutines.reactive.awaitSingle
import org.springframework.stereotype.Component

@Component
class DemoHandler {

    fun get() = json { req ->
        if (req.pathVariable("whatever") == "error") {
            throw RuntimeException("ddd")
        }
        req.pathVariables()
    }

    fun post() = json { req ->
        val dto = req.body(DemoPostDto::class.java).awaitSingle()
        mapOf("name" to dto.name, "age" to dto.age)
    }

    fun renderError() = render {
        throw unhandled()
    }

    fun session() = json {
        // 验证 session 是否可以发送多次
        val session = it.session()
        val session2 = it.session()
        mapOf("is the same" to (session === session2))
    }

    fun body() = json {
        val dto = it.body(DemoPostDto::class.java).awaitSingle()
        val dto2 = it.body(DemoPostDto::class.java).awaitSingle()
        mapOf("is the same" to (dto.name == dto2.name))
    }
}

internal class DemoPostDto(val name: String, val age: String)

